package com.nowcoder.community.service;

import com.nowcoder.community.dao.MessageMapper;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;

    /**
     * 查询当前用户的会话列表,针对每个会话只返回一条最新的私信.
     * @author ProgramCat
     * @date 2023/3/31 22:02
     * @param userId 用户id
     * @param offset 起始行
     * @param limit 每页显示上限
     * @return List<Message>
     */
    public List<Message> findConversations(int userId,int offset,int limit){
        return messageMapper.selectConversations(userId,offset,limit);
    }

    /**
     * 查询当前用户的会话数量.
     * @author ProgramCat
     * @date 2023/3/31 23:55
     * @param userId 用户id
     * @return int
     */
    public int findConversationCount(int userId) {
        return messageMapper.selectConversationCount(userId);
    }
    /**
     *查询某个会话所包含的私信数量.
     * @author ProgramCat
     * @date 2023/3/31 22:12
     * @param conversationId 会话id
     * @return int 会话所包含的私信数量
     */
    public List<Message> findLetters(String conversationId, int offset, int limit) {
        return messageMapper.selectLetters(conversationId, offset, limit);
    }
    /**
     *查询某个会话所包含的私信数量.
     * @author ProgramCat
     * @date 2023/3/31 22:12
     * @param conversationId 会话id
     * @return int 会话所包含的私信数量
     */
    public int findLetterCount(String conversationId) {
        return messageMapper.selectLetterCount(conversationId);
    }
    /**
     * 查询未读私信的数量
     * @author ProgramCat
     * @date 2023/3/31 22:13
     * @param userId 用户id
     * @param conversationId 会话 id
     * @return int 未读私信的数量
     */
    public int findLetterUnreadCount(int userId, String conversationId) {
        return messageMapper.selectLetterUnreadCount(userId, conversationId);
    }
    /**
     * 新增 私聊消息
     * @author ProgramCat
     * @date 2023/4/1 15:10
     * @param message 私聊消息实体
     * @return int
     */
    public int addMessage(Message message) {
        message.setContent(HtmlUtils.htmlEscape(message.getContent()));
        message.setContent(sensitiveFilter.filter(message.getContent()));
        return messageMapper.insertMessage(message);
    }
    /**
     * 修改消息的状态
     * @author ProgramCat
     * @date 2023/4/1 15:10
     * @param ids 未读消息id 集合
     * @return int
     */
    public int readMessage(List<Integer> ids) {
        return messageMapper.updateStatus(ids, 1);
    }
}
